﻿using AntdUI;
using Lima.ResumeSys.DAL;
using Lima.ResumeSys.Models;
using Lima.ResumeSys.PersonControl;
using Lima.ResumeSys.Util;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using static Lima.ResumeSys.Util.PersonEnums;

namespace Lima.ResumeSys
{
    public partial class PersonInfoForm : AntdUI.Window
    {
        PerSonInfoDAL dal = new PerSonInfoDAL();
        OrganizationDAL orgdal = new OrganizationDAL();
        SysUtil util = new SysUtil();
        /// <summary>
        /// 用户主键参数
        /// </summary>
        private string _PerNo = "";
        private byte[] perPhoto = null;
        private bool result = false;
        private string _CurrentOrgId = "";
        public PersonInfoForm(string perNo, string currentOrgId)
        {
            _PerNo = perNo;
            _CurrentOrgId = currentOrgId;
            InitializeComponent();
            BindDropDownTreeViewData();//绑定下拉框数据
            InitializePerInfo();//基本信息
            GetPerInfoModel();

            tabs1.SelectedIndex = 0;
        }

        /// <summary>
        /// 绑定下拉框组织数据
        /// </summary>
        private void BindDropDownTreeViewData()
        {
            var dataTable = orgdal.GetTreeViewData();

            var allData = dataTable.AsEnumerable().Select(row => new Organization
            {
                ID = row["Id"].ToString(),
                Code = row["Code"].ToString(),
                OrgName = row["OrgName"].ToString(),
                ParCode = row["ParCode"].ToString(),
            }).ToList();

            TreeBuilder treeBuilder = new TreeBuilder();
            treeBuilder.BindDropDownWithParentId(orgSelect, allData, CurrentUser.UserOrgId);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #region  From 数据绑定
        /// <summary>
        /// PerInfo
        /// </summary>
        private void GetPerInfoModel()
        {
            if (!string.IsNullOrWhiteSpace(_PerNo))
            {
                #region 基本信息
                PersonInfo entity = dal.GetModel(_PerNo);
                PerName.Text = entity.PerName;
                radmale.Checked = entity.PerSex == "男";
                radfemale.Checked = entity.PerSex == "女";  // 假设有 radfemale 控件
                orgSelect.SelectedText = entity.PerOrgName;
                orgSelect.SelectedValue = entity.PerOrgId;
                orgSelect.Text = entity.PerOrgName;
                // 日期字段需要特殊处理
                PerBirth.Value = entity.PerBirth;
                PerFormerName.Text = entity.PerFormerName;
                PerNationality.Text = entity.PerNationality;
                PerIdCard.Text = !string.IsNullOrWhiteSpace(entity.PerIdCard)? Sm4Crypto.Decrypt_ECB_Str(entity.PerIdCard):""; 
                PerNativePlace.Text = entity.PerNativePlace;
                PerMaritalStatus.Text = entity.PerMaritalStatus;
                PerEducationLevel.Text = entity.PerEducationLevel;
                PerPoliticalStatus.Text = entity.PerPoliticalStatus;
                if (entity.PerJoinPartyTime != null)
                {
                    PerJoinPartyTime.Value = entity.PerJoinPartyTime;
                }
                if (entity.PerWorkStartTime != null)
                {
                    PerWorkStartTime.Value = entity.PerWorkStartTime;
                }
                PerUnitNature.Text = entity.PerUnitNature;
                PerJobPosition.Text = entity.PerJobPosition;
                PerJobLevel.Text = entity.PerJobLevel;
                PerJobTitle.Text = entity.PerJobTitle;
                PerManagementWork.Text = entity.PerManagementWork;
                if (entity.PerTenureTime != null)
                {
                    PerTenureTime.Value = entity.PerTenureTime;
                }
                PerAddress.Text = entity.PerAddress;

                // 处理照片数据
                if (!string.IsNullOrEmpty(entity.PerPhoto))
                {
                    perPhoto = Convert.FromBase64String(entity.PerPhoto);
                    imgPhoto.Image = util.ByteArrayToImage(perPhoto);
                }
                #endregion

            }
        }
        #endregion

        #region 基本信息
        #region 基本信息初始化

        private void BindEventHandler()
        {
            //1.7.14开始,uploadDragger自带点击打开文件选择框
            upPhoto.DragChanged += upPhoto_DragChanged;
            upPhoto.Multiselect = false;//允许多选文件
            upPhoto.Filter = "Image Files (*.jpg; *.jpeg; *.png; *.gif; *.bmp)|*.jpg;*.jpeg;*.png;*.gif;*.bmp";
            upPhoto.HandDragFolder = false;//是否支持拖拽，默认为true
        }


        #region  基本信息初始加载
        public void InitializePerInfo()
        {
            BindEventHandler();// 上传控件
            //文化程度
            PerEducationLevel.Items.AddRange(
                Enum.GetValues(typeof(EducationLevel))
                    .Cast<EducationLevel>()
                    .Select(x => new SelectItem(x.ToString()))
                    .ToArray()
            );

            //政治面貌
            PerPoliticalStatus.Items.AddRange(
                Enum.GetValues(typeof(PoliticalStatus))
                    .Cast<PoliticalStatus>()
                    .Select(x => new SelectItem(x.ToString()))
                    .ToArray()
            );


            //婚姻状况
            PerMaritalStatus.Items.AddRange(
                Enum.GetValues(typeof(MaritalStatus))
                    .Cast<MaritalStatus>()
                    .Select(x => new SelectItem(x.ToString()))
                    .ToArray()
            );

        }

        private void upPhoto_DragChanged(object sender, StringsEventArgs e)
        {
            string[] filePaths = e.Value;
            foreach (string path in filePaths)
            {
                perPhoto = util.FileToByteArray(path);
            }
            imgPhoto.Image = util.ByteArrayToImage(perPhoto);
        }
        #endregion

        #endregion
        /// <summary>
        /// 绑定用户基本信息
        /// </summary>
        private void btnPerInfoSave_Click(object sender, EventArgs e)
        {
            result = false;
            if (string.IsNullOrWhiteSpace(PerIdCard.Text) || string.IsNullOrWhiteSpace(PerName.Text) || string.IsNullOrWhiteSpace(PerBirth.Text) || string.IsNullOrWhiteSpace(PerWorkStartTime.Text) ||
                string.IsNullOrEmpty(this.orgSelect.SelectedValue.ToString()))
            {
                MessageBox.Show("员工信息不完整,无法添加！带*为必填项", "提示", MessageBoxButtons.OK);
            }
            else
            {
                if (!util.IsIdCardChecksumValid(PerIdCard.Text))
                {
                    MessageBox.Show("身份证号输入有误!", "提示", MessageBoxButtons.OK);
                    return;
                }

                if (dal.GetResultCount(PerIdCard.Text.ToString()) > 0)
                {
                    MessageBox.Show("该人员信息已存在!", "提示", MessageBoxButtons.OK);
                    return;
                }

                PersonInfo entity = new PersonInfo();
                entity.PerName = PerName.Text.Trim();
                entity.PerSex = radmale.Checked == true ? "男" : "女";
                if (!string.IsNullOrWhiteSpace(PerBirth.Text))
                {
                    entity.PerBirth = DateTime.ParseExact(PerBirth.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                }
                entity.PerFormerName = PerFormerName.Text.Trim();
                entity.PerNationality = PerNationality.Text.Trim();
                entity.PerIdCard = Sm4Crypto.Encrypt_ECB_Str(PerIdCard.Text.Trim());
                entity.PerNativePlace = PerNativePlace.Text.Trim();
                entity.PerMaritalStatus = PerMaritalStatus.Text.Trim();
                entity.PerEducationLevel = PerEducationLevel.Text.Trim();
                entity.PerPoliticalStatus = PerPoliticalStatus.Text.Trim();
                if (!string.IsNullOrWhiteSpace(PerJoinPartyTime.Text))
                {
                    entity.PerJoinPartyTime = DateTime.ParseExact(PerJoinPartyTime.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                }
                if (!string.IsNullOrWhiteSpace(PerWorkStartTime.Text))
                {
                    entity.PerWorkStartTime = DateTime.ParseExact(PerWorkStartTime.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                }
                entity.PerUnitNature = PerUnitNature.Text.Trim();
                entity.PerJobPosition = PerJobPosition.Text.Trim();
                entity.PerJobLevel = PerJobLevel.Text.Trim();
                entity.PerJobTitle = PerJobTitle.Text.Trim();
                entity.PerManagementWork = PerManagementWork.Text.Trim();
                entity.PerOrgId = this.orgSelect.SelectedValue.ToString();
                entity.PerOrgName = this.orgSelect.Text;

                if (!string.IsNullOrWhiteSpace(PerTenureTime.Text))
                {
                    entity.PerTenureTime = DateTime.ParseExact(PerTenureTime.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                }
                entity.PerAddress = PerAddress.Text.Trim();
                if (perPhoto != null)
                {
                    entity.PerPhoto = Convert.ToBase64String(perPhoto);
                }
                else
                {
                    string baseDir = AppDomain.CurrentDomain.BaseDirectory; // bin\Debug\net6.0
                    string imagePath = Path.Combine(baseDir, @"..\..\Resources\photo.png");
                    entity.PerPhoto = Convert.ToBase64String(util.FileToByteArray(imagePath));
                }

                if (string.IsNullOrWhiteSpace(_PerNo))
                {
                    entity.PerNo = Guid.NewGuid().ToString();
                    entity.Creator = CurrentUser.UserName;
                    entity.UpdatedBy = "";
                    _PerNo = entity.PerNo;
                    result = dal.Add(entity);
                }
                else
                {
                    entity.PerNo = _PerNo;
                    entity.UpdatedBy = CurrentUser.UserName;
                    result = dal.Update(entity);
                }
                if (result)
                {
                    AntdUI.Message.success(this, "操作成功！", autoClose: 3);
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btncancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion



        private void tabs1_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            // 如果 _PerNo 为空，并且用户尝试切换到非第一个选项卡
            if (string.IsNullOrEmpty(_PerNo) && tabs1.SelectedIndex != 0)
            {
                AntdUI.Message.error(this, "请先保存员工基本信息！", autoClose: 3);
                tabs1.SelectedIndex = 0; // 强制回到第一个选项卡
                return;
            }
            var name = tabs1.SelectedTab.Text;
            switch (name)
            {
                case "附件信息":
                    UserControl control = new EditFIle(this, this._PerNo);
                    //容器添加控件，需要调整dpi
                    control.Dock = DockStyle.Fill;
                    AutoDpi(control);
                    tabPage6.BackColor = Color.White;
                    tabPage6.Controls.Add(control);
                    break;
                case "奖惩信息":
                    UserControl rewardPunish = new EditRewardPunish(this, this._PerNo);
                    //容器添加控件，需要调整dpi
                    rewardPunish.Dock = DockStyle.Fill;
                    AutoDpi(rewardPunish);
                    tabPage3.BackColor = Color.White;
                    tabPage3.Controls.Add(rewardPunish);
                    break;

            }


        }

        private void PersonInfoForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult = DialogResult.OK;
        }
    }
}
